package com.example.studyFile.asynchronousOptimization;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * 异步优化方案
 */
public class AsyncValidationExample {

    private final ExecutorService executorService = Executors.newFixedThreadPool(10);

    public void executeValidations() throws Exception {
        List<Callable<Void>> validationTasks = Arrays.asList(
            this::validation1,
            this::validation2,
            this::validation3
            // 添加更多校验方法
        );


        List<CompletableFuture<Void>> futures = validationTasks.stream()
            .map(task -> CompletableFuture.runAsync(() -> {
                try {
                    task.call();
                } catch (Exception e) {
                    throw new CompletionException(e);  // 将异常包装为 CompletionException
                }
            }, executorService))
            .collect(Collectors.toList());

        try {
            // 等待所有任务完成，如果有任何异常则抛出
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        } catch (CompletionException e) {
            // 捕获并抛出第一个发生的异常
            System.out.println("e = " + e.getMessage());
            throw (Exception) e.getCause();
        } finally {
            executorService.shutdown();
        }
    }

    // 示例校验方法
    private Void validation1() throws Exception {
        // 校验逻辑
        System.out.println("executorService1");
        return null;
    }

    private Void validation2() throws Exception {
        // 校验逻辑
        System.out.println("executorService 2 ");
        return null;
    }

    private Void validation3() throws Exception {
        throw new BusinessException("Validation failed123123");
        // 校验逻辑
//        return null;
    }

    public static void main(String[] args) {
        AsyncValidationExample example = new AsyncValidationExample();
        try {
            example.executeValidations();
            System.out.println("所有校验完成");
        } catch (Exception e) {
            System.err.println("校验失败: " + e.getMessage());
        }
    }
}
